﻿using System;
using System.Linq.Expressions;

namespace Unis.Framework.ORM.Common
{
    public class ExpressionHelper
    {
        // Methods
        public static string GetMethodName<T>(Expression<Action<T>> expression)
        {
            return GetNameFromLambda(expression);
        }

        private static string GetNameFromLambda(LambdaExpression lambda)
        {
            MemberExpression operand = null;
            if (lambda.Body is UnaryExpression)
            {
                UnaryExpression expression2 = lambda.Body as UnaryExpression;
                operand = expression2.Operand as MemberExpression;
            }
            else if (lambda.Body is MemberExpression)
            {
                operand = lambda.Body as MemberExpression;
            }
            if (operand != null)
            {
                return operand.Member.Name;
            }
            if (!(lambda.Body is MethodCallExpression))
            {
                throw new ArgumentException(string.Format("Expression '{0}' 没有提供方法的名称或者属性的名称.", lambda));
            }
            MethodCallExpression body = lambda.Body as MethodCallExpression;
            return body.Method.Name;
        }

        public static string GetPropertyName<T>(Expression<Action<T>> expression)
        {
            return GetNameFromLambda(expression);
        }

        public static string GetPropertyName<T>(Expression<Func<T>> expression)
        {
            return GetNameFromLambda(expression);
        }

        public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
        {
            return GetNameFromLambda(expression);
        }
    }
}
